package com.miku.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.blog.domain.Resource;
import com.miku.blog.domain.dto.ResourceURIDTO;
import com.miku.blog.domain.dto.ResourceUserDTO;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.domain.dto.ResourceDTO;
import com.miku.blog.domain.vo.ResourceVo;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.exception.SystemException;
import com.miku.blog.service.ResourceService;
import com.miku.blog.mapper.ResourceMapper;
import com.miku.blog.utils.BeanCopyUtils;
import com.miku.blog.utils.PathUtils;
import com.miku.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Miku
 * @description 针对表【tb_resource】的数据库操作Service实现
 * @createDate 2022-06-01 22:06:09
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource>
        implements ResourceService {


    @Autowired
    private RedisCache redisCache;


    @Override
    public Map<String, List<ResourceUserDTO>> getResourcesByRoleId(Integer roleId) {

        List<Resource> childrenList = baseMapper.getChildrenResourcesByRoleId(roleId);
        Map<String, List<ResourceUserDTO>> map = new HashMap<>();
        if (Objects.nonNull(childrenList) && childrenList.size() > 0) {
            map = getResourceMap(childrenList);
        }

        return map;
    }


    @Override
    public Map<String, List<ResourceUserDTO>> getResourceMap(List<Resource> resourceList) {
        Map<String, List<ResourceUserDTO>> map = new HashMap<>();
        resourceList.stream()
                .peek(resource -> {
                    if (SystemConstance.RESOURCE_ROOT_ID.equals(resource.getParentId())) {
                        return;
                    }
                    ResourceUserDTO resourceUserDTO = BeanCopyUtils.copyObjectByType(resource, ResourceUserDTO.class);
                    String prefix = PathUtils.getPathPrefix(resource.getUrl());
                    if (map.containsKey(prefix)) {
                        List<ResourceUserDTO> resourceUserDTOList = map.get(prefix);
                        resourceUserDTOList.add(resourceUserDTO);
                    } else {
                        ArrayList<ResourceUserDTO> list = new ArrayList<>();
                        list.add(resourceUserDTO);
                        map.put(prefix, list);
                    }
                }).collect(Collectors.toList());
        return map;
    }


    @Override
    public ResponseResult getResources() {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getParentId, SystemConstance.RESOURCE_ROOT_ID);
        List<Resource> resourceList = list(queryWrapper);
        List<ResourceDTO> resourceDTOList = null;
        if (Objects.nonNull(resourceList) && resourceList.size() > 0) {
            resourceDTOList
                    = resourceList.stream()
                    .map(resource -> {
                        ResourceDTO resourceDTO = new ResourceDTO();
                        queryWrapper.clear();
                        queryWrapper.eq(Resource::getParentId, resource.getId());
                        List<Resource> var1 = list(queryWrapper);
                        if (Objects.nonNull(var1) && var1.size() > 0) {
                            List<ResourceDTO> children
                                    = var1.stream()
                                    .map(var11 -> {
                                        ResourceDTO var12 = new ResourceDTO();
                                        var12.setLabel(var11.getResourceName())
                                                .setId(var11.getId());
                                        return var12;
                                    }).collect(Collectors.toList());
                            resourceDTO.setChildren(children);
                        }
                        resourceDTO.setId(resource.getId())
                                .setLabel(resource.getResourceName());
                        return resourceDTO;
                    }).collect(Collectors.toList());
        }
        return ResponseResult.ok().setData(resourceDTOList);
    }


    @Override
    public ResponseResult getResourceList(@Nullable String keywords) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getParentId, SystemConstance.RESOURCE_ROOT_ID)
                .orderByAsc(Resource::getCreateTime);
        List<Resource> roots = list(queryWrapper);
        List<ResourceVo> rootVos = BeanCopyUtils.copyListByType(roots, ResourceVo.class);
        rootVos = rootVos.stream()
                .peek(vo -> {
                    queryWrapper.clear();
                    queryWrapper.eq(Resource::getParentId, vo.getId())
                            .like(StringUtils.hasText(keywords), Resource::getResourceName, keywords)
                            .orderByAsc(Resource::getCreateTime);
                    List<Resource> children = list(queryWrapper);
                    if (Objects.nonNull(children) && children.size() > 0) {
                        List<ResourceVo> voList = BeanCopyUtils.copyListByType(children, ResourceVo.class);
                        vo.setChildren(voList);
                    }
                })
                .collect(Collectors.toList());
        return ResponseResult.ok().setData(rootVos);
    }


    @Override
    public ResponseResult addResource(Resource resource) {
        if (!StringUtils.hasText(resource.getResourceName())) {
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }

        Integer isAnonymous = resource.getIsAnonymous();
        String method = resource.getRequestMethod();
        String url = resource.getUrl();
        Integer parentId = resource.getParentId();

        Integer id = resource.getId();

        if (Objects.isNull(id)) {
            //新增主菜单 isAnonymous = null ,parentId = null
            //新增子菜单 isAnonymous = null ,parentId != null
            if (Objects.nonNull(isAnonymous)
                    || Objects.nonNull(parentId) && (!StringUtils.hasText(method) || !StringUtils.hasText(url))
            ) {
                return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
            }
            if (!save(resource)) {
                return new ResponseResult(HttpStatusEnum.INSERT_DATA_ERROR);
            }
        } else {
            LambdaUpdateWrapper<Resource> updateWrapper = new LambdaUpdateWrapper<>();
            if (SystemConstance.RESOURCE_ROOT_ID.equals(parentId)) {
                updateWrapper.eq(Resource::getId, id)
                        .set(Resource::getResourceName, resource.getResourceName())
                        .set(Resource::getUpdateTime, new Date());
                if (!update(updateWrapper)) {
                    return new ResponseResult(HttpStatusEnum.UPDATE_DATA_ERROR);
                }
            } else {
                if (Objects.isNull(isAnonymous)
                        || !StringUtils.hasText(method) || !StringUtils.hasText(url)
                        || (!isAnonymous.equals(SystemConstance.IS_ANONYMOUS) && !isAnonymous.equals(SystemConstance.NOT_ANONYMOUS))
                        || Objects.isNull(getById(parentId))
                ) {
                    return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
                }
                if (!updateById(resource)) {
                    return new ResponseResult(HttpStatusEnum.UPDATE_DATA_ERROR);
                }

            }
        }
        return ResponseResult.ok();
    }


    @Override
    public ResponseResult isAnonymous(Integer resourceId, Integer isAnonymous) {
        if ((!isAnonymous.equals(SystemConstance.IS_ANONYMOUS) && !isAnonymous.equals(SystemConstance.NOT_ANONYMOUS))
        ) {
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }
        LambdaUpdateWrapper<Resource> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Resource::getId, resourceId)
                .set(Resource::getIsAnonymous, isAnonymous);
        if (!update(updateWrapper)) {
            return new ResponseResult(HttpStatusEnum.UPDATE_DATA_ERROR);
        }

        updateRedisResource(resourceId);

        return ResponseResult.ok();
    }


    /**
     * 删除资源模块不考虑同步redis
     * @param resourceIdList
     * @return
     */
    @Transactional
    @Override
    public ResponseResult deleteResource(Integer[] resourceIdList) {

        for (Integer resourceId : resourceIdList) {

            Resource resource = getById(resourceId);
            if (resource.getParentId().equals(SystemConstance.RESOURCE_ROOT_ID)) {
                LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Resource::getParentId, resourceId);
                List<Resource> children = list(queryWrapper);
                if (Objects.nonNull(children) && children.size() > 0) {
                    children.stream()
                            .peek(re -> {
                                baseMapper.deleteTBRoleResourceByResourceId(re.getId());
                                if (!removeById(re.getId())) {
                                    throw new SystemException(HttpStatusEnum.REMOVE_DATA_ERROR);
                                }
                            }).collect(Collectors.toList());
                }
            }
            baseMapper.deleteTBRoleResourceByResourceId(resourceId);
            if (!removeById(resourceId)) {
                throw new SystemException(HttpStatusEnum.REMOVE_DATA_ERROR);
            }

        }

        return ResponseResult.ok();
    }


    @Override
    public List<Resource> getResourceChildrenList() {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Resource::getParentId, SystemConstance.RESOURCE_ROOT_ID);
        return list(queryWrapper);
    }


    private void updateRedisResource(Integer resourceId) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getId, resourceId);
        Resource resource = getOne(queryWrapper);


        String url = resource.getUrl();

        String prefix = PathUtils.getPathPrefix(url);

        List<ResourceURIDTO> resourceList = redisCache.getCacheHashMapValue(SystemConstance.RESOURCE_REQUEST_URI_LIST_KEY, prefix);
        if (Objects.isNull(resourceList)) {
            return;
        }
        for (ResourceURIDTO dto : resourceList) {
            if (resource.getUrl().equals(dto.getUrl()) && resource.getRequestMethod().equals(dto.getRequestMethod())) {
                dto.setIsAnonymous(resource.getIsAnonymous());
                redisCache.setCacheHashMap(SystemConstance.RESOURCE_REQUEST_URI_LIST_KEY, prefix, resourceList);
                break;
            }
        }
    }


}




